import { openKv } from "@deno/kv";
import { serialize as encodeV8, deserialize as decodeV8 } from "v8"; // actually JavaScriptCore format on Bun!
import { model, collection, kvdex } from "@olli/kvdex";
import { mkdir } from "node:fs/promises";

type User = {
    username: string;
    age: number;
    activities: string[];
    address?: {
        country: string;
        city: string;
        street: string;
        houseNumber: number | null;
    };
};

// Normal model (equal input and output)
const UserModel = model<User>();
//不存在db文件夹则创建
await mkdir("db/", { recursive: true });
const kv = await openKv("db/kv.db", { encodeV8, decodeV8 });
export const db = kvdex({
    kv: kv,
    schema: {
        users: collection(UserModel, {
            history: true,
            indices: {
                username: "primary", // unique
                age: "secondary" // non-unique
            }
        }),
    }
})